#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include "fs4412_pwm/pwm_music.h"
#include "fs4412_led/driver/fs4412_led.h"
#include "fs4412_pwm/driver/fs4412_pwm.h"

#include <signal.h>

int fd1,fd2,fd3;

void pwm(int data)
{
    int div;
    int n=1024;
    switch (data) {
        case 1:
            div = (PCLK/n/4)/DO;
            ioctl(fd2,SET_CNT,&div);
            break;
        case 2:
            div = (PCLK/n/4)/RE;
            ioctl(fd2,SET_CNT,&div);
            break;
        case 3:
            div = (PCLK/n/4)/MI;
            ioctl(fd2,SET_CNT,&div);
            break;
        case 4:
            div = (PCLK/n/4)/FA;
            ioctl(fd2,SET_CNT,&div);
            break;
        case 5:
            div = (PCLK/n/4)/SOL;
            ioctl(fd2,SET_CNT,&div);
            break;
        case 6:
            div = (PCLK/n/4)/LA;
            ioctl(fd2,SET_CNT,&div);
            break;
        case 7:
            div = (PCLK/n/4)/SI;
            ioctl(fd2,SET_CNT,&div);
            break;
        case 8:
            div = (PCLK/n/4)/DOL;
            ioctl(fd2,SET_CNT,&div);
            break;
    }
}

void led(int data)
{
    int d1 = (data+1);
    int d2 = (data+2);
    int d3 = (data-4);
    int d4 = (data-3);

    switch (data) {
    case 4:
    case 3:
    case 2:
    case 1:
    case 0:ioctl(fd1,LED_ON,&d1);
    }

    switch (data) {
    case 4:ioctl(fd1,LED_ON,&d4);
    case 3:
    case 2:
    case 1:
    case 0:
        ioctl(fd1,LED_OFF,&d2);
        break;
    case 5:
    case 6:
    case 7:
        ioctl(fd1,LED_ON,&d4);
        ioctl(fd1,LED_OFF,&d3);
    }
}

int adc(int *data){
    int offset;
    float v;
    read(fd3,data, sizeof(*data));
    v=1.8 * (*data) / 4096;            //计算电压,电压最大值约为1.20
    printf("is : %0.2fV\n", v);
    //电压最大值约为1.20,将电压均分为八份，返回0~7
    offset = v/(1.20/8);
    return offset;
}

void end(int sig){
    printf("程序结束。");
    ioctl(fd2,PWM_OFF);
    exit(0);
}


int main(int argc, const char *argv[])
{
    signal(SIGINT,end);

    int data;
    int pre;
    fd1 = open("/dev/led", O_RDWR);//打开通过mknod命令创建的设备文件
    fd2 = open("/dev/pwm",O_RDWR | O_NONBLOCK);
    fd3 = open("/dev/adc", O_RDWR);
    if (fd1 < 0 || fd2<0 || fd3<0) {
            perror("open");
            exit(1);
    }

    ioctl(fd2,PWM_ON);

    while(1) {

        int num=0;
        num = adc(&data);
        printf("num = %d\n",num);
        led(num);
        pwm(num+1);
        usleep(1);//等待1umm

    }


    return 0;
}
